import puppeteer from 'puppeteer-core';
import { hasClass, stockListMerge, parseStockData, saveStock, getIndustryData, extractMarketSentiment } from './utils.js';

(async () => {

  const browser = await puppeteer.launch({
    headless: true,
    executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe'
  });

  const page = await browser.newPage();

  await page.evaluateOnNewDocument(() => {
    Object.defineProperty(navigator, 'webdriver', {
      get: () => false,
    });
  });
  await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36');

  // 设置 viewport 模拟常见的分辨率
  await page.setViewport({ width: 1920, height: 1080 });

  const target = 'https://www.iwencai.com/unifiedwap/home/index'
  page.goto(target)


  await page.waitForSelector('#searchInput')


  // ,热门50股, 尾盘资金流入占全天成交比例≥20%, , 排除当日涨停炸板

  // const example_1 = '成交量放大;阳包阴或者长下影线;主力资金净流入;主板;排除涨停板'
  const example_2 = '热门前500股;排除涨停;排除跌停;主板;排除市值>1000亿;'
  // 买入信号;卖出信号
  const example_3 = '热门前500股;排除涨停;排除跌停;主板;排除市值>1000亿;振幅;3日主力资金;5日主力资金;10日主力资金;macd值;3日均线;5日均线;10日均线;资金流向;3日资金流向;5日资金流向;10日资金流向;量比;支撑位;压力位;均价;当日最高涨幅;买入信号;卖出信号;'
  // const example_3 = '成交量持续放大;主力资金净流入占总成交比例 ≥10%;阳包阴或长下影线;主板;涨幅 < 7%;振幅<=8%'
  // const example_1 = '当日成交量大于五日成交量均线1.5倍;主板;排除当日涨停;排除st,主力资金净流入'
  // const example_4 = '主力资金净流入;当日最高价/现价 > 1.05;主板'

  await page.type('textarea#searchInput', example_3)

  await page.keyboard.press("Enter")


  await page.waitForSelector('.select-box-wrap')


  await page.waitForSelector('.iwc-table-content .iwc-table-body table')

  // 将 hasClass 函数暴露给页面
  await page.exposeFunction('hasClass', hasClass);

  await page.exposeFunction('parseStockData', parseStockData);

  await page.exposeFunction('stockListMerge', stockListMerge);

  const res = await page.evaluate(async function (param) {
    const { example_2, example_3 } = param

    // 扩大页码
    await new Promise(resolve => setTimeout(resolve, 1000));
    document.querySelectorAll('.pcwencai-pagination-wrap .drop-down-box ul li')[2].click()

    const obj = {
      // '相关': 0,
      '概况': 1,
      '表现': 2,
      '技术': 3,
      '估值': 4
    }
    const res = {}

    const keywords = example_3.replace(example_2, '').split(';').filter(Boolean);
    const groupSize = 4;

    // 遍历关键词数组，每4个一组
    for (let i = 0; i < keywords.length; i += groupSize) {
      const group = keywords.slice(i, i + groupSize);
      const keyWord = group.join(';');

      await setInputValue(`${example_2}${keyWord};`)
      // 等待元素内容更新
      await waitForElementUpdate('#iwc-table-container');

      await pageHTMLToData('相关')
    }


    await setInputValue(example_2)
    await waitForElementUpdate('#iwc-table-container')
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        const index = obj[key];
        await new Promise(resolve => setTimeout(resolve, 500));
        document.querySelectorAll('.XuanguTab.XuanguTab .tab-item')[index].click()


        // 等待页面切换完成
        let isLoop = true
        while (isLoop) {
          const isSelect = await hasClass(document.querySelectorAll('.XuanguTab.XuanguTab .tab-item')[index], 'tab-item-selected')
          console.log(isSelect);
          isLoop = !isSelect
          await new Promise(resolve => setTimeout(resolve, 500));
        }

        await pageHTMLToData(key)
      }
    }
    // 输入内容
    async function setInputValue (value) {
      // 获取输入框元素
      const input = document.querySelector('textarea#searchInput');
      if (!input) {
        console.error('输入框未找到');
        return;
      }
      input.value = value;

      // 触发 input 事件（如果需要）
      const inputEvent = new Event('input', { bubbles: true });
      input.dispatchEvent(inputEvent);

      // 触发 change 事件（如果需要）
      const changeEvent = new Event('change', { bubbles: true });
      input.dispatchEvent(changeEvent);

      // 获取搜索按钮并点击
      const searchButton = document.querySelector('.search-bar-icon.search-icon.pointer');
      if (!searchButton) {
        console.error('搜索按钮未找到');
        return;
      }
      searchButton.click();
    }
    // 等待元素内容更新
    function waitForElementUpdate (selector) {
      return new Promise((resolve) => {
        const element = document.querySelector(selector);
        if (!element) {
          console.error('目标元素未找到');
          resolve(); // 如果元素不存在，直接解析（或根据需求抛出错误）
          return;
        }

        const observer = new MutationObserver(() => {
          observer.disconnect(); // 监听到变化后断开观察者
          resolve(); // 解析 Promise
        });

        // 配置观察者，监听内容变化
        observer.observe(element, {
          childList: true,      // 监听子元素的变化
          subtree: true,        // 监听整个子树的变化
          characterData: true   // 监听文本内容的变化
        });
      });
    }

    // 解析页面内容
    async function pageHTMLToData (key) {
      const table = document.querySelector('#iwc-table-container')
      if (table?.innerHTML) {
        const data = await parseStockData(table.innerHTML)
        if (res[key]) {
          res[key] = await stockListMerge(res[key], data, '股票代码')
        } else {
          res[key] = data
        }
        const liList = document.querySelectorAll('.pcwencai-pagination li')
        const lastLi = liList[liList.length - 1]
        let isOver = await hasClass(lastLi, 'disabled')
        while (!isOver) {
          lastLi.querySelector('a').click()
          await waitForElementUpdate('#iwc-table-container');
          const table = document.querySelector('#iwc-table-container')
          const data = await parseStockData(table.innerHTML)
          res[key] = await stockListMerge(res[key], data, '股票代码')
          isOver = await hasClass(lastLi, 'disabled')
        }
      } else {
        console.log('未获取到dom');
      }
    }

    return res

  }, { example_2, example_3 })

  const relatedList = res['相关']

  const overviewList = res['概况']

  const performanceList = res['表现']

  const technologyList = res['技术']

  const valuationList = res['估值']


  const stockList = []

  technologyList.forEach((item, index) => {
    const relatedItem = relatedList.find((ele) => ele['股票代码'] === item['股票代码']) ?? {}
    const overviewItem = overviewList.find((ele) => ele['股票代码'] === item['股票代码']) ?? {}
    const performanceItem = performanceList.find((ele) => ele['股票代码'] === item['股票代码']) ?? {}
    const valuation = valuationList.find((ele) => ele['股票代码'] === item['股票代码']) ?? {}

    if (!performanceItem['股票代码']) {
      console.log('表现: ', item['股票简称']);
    }
    if (!overviewItem['股票代码']) {
      console.log('概况', item['股票简称']);
    }
    if (!relatedItem['股票代码']) {
      console.log('相关', item['股票简称']);
      return
    }

    stockList.push({
      ...item,
      '现价(元)': item['现价(元)'],
      '当日开盘价(元)': relatedItem['开盘价:不复权(元)'],
      '当日最低价(元)': relatedItem['最低价:不复权(元)'],
      '当日最高价(元)': relatedItem['最高价:不复权(元)'],
      '支撑位': relatedItem['止盈止损(支撑位)'],
      '压力位': relatedItem['止盈止损(压力位)'],
      'macd值': relatedItem['macd(macd值)'],
      '量比': relatedItem['量比'],
      '当日最大涨幅(%)': relatedItem['最大涨幅(%)'],
      '振幅(%)': relatedItem['振幅(%)'],
      '当日资金流向(元)': relatedItem['资金流向(元)'],
      '全部资金流向3日(元)': relatedItem['区间资金流向(元)3日'],
      '全部资金流向5日(元)': relatedItem['区间资金流向(元)5日'],
      '全部资金流向10日(元)': relatedItem['区间资金流向(元)10日'],
      '流通市值(元)': valuation['a股流通市值(元)'],
      '成交量(股)': overviewItem['成交量(股)'],
      '成交额(元)': overviewItem['成交额(元)'],
      '所属行业': overviewItem['所属同花顺行业'],
      '公司简介': overviewItem['公司简介'],
      '主力资金流向3日(元)': relatedItem['区间主力资金流向(元)3日'],
      '主力资金流向5日(元)': relatedItem['区间主力资金流向(元)5日'],
      '主力资金流向10日(元)': relatedItem['区间主力资金流向(元)10日'],
      '当日均价': relatedItem['均价:不复权(元)'],
      '3日均线': relatedItem['3日均线'],
      '5日均线': relatedItem['5日均线'],
      '10日均线': relatedItem['10日均线'],
      "近3日涨幅(%)": performanceItem["近3日涨幅(%)"],
      "近5日涨幅(%)": performanceItem["近5日涨幅(%)"],
      "近10日涨幅(%)": performanceItem["近10日涨幅(%)"],
      "买入信号": relatedItem["买入信号"],
      "卖出信号": relatedItem["卖出信号"],
    })

  })


  let sentiment = {}

  page.on('response', async (response) => {
    const url = response.url();
    if (url.includes('get-robot-data')) {
      try {
        const data = await response.text();

        sentiment = extractMarketSentiment(JSON.parse(data))
      } catch (error) {
        // 如果不是 JSON 格式，获取文本内容
        console.error('Error parsing JSON:', error);
      }
    }
  });

  // 市场情绪
  await page.goto('https://www.iwencai.com/unifiedwap/result?w=%E7%9F%AD%E7%BA%BF%E5%A4%8D%E7%9B%98&querytype=&issugs')


  await page.waitForSelector('.card_container.card_container_pc')

  await page.waitForSelector('.jgy_txt.jgy_txt_isLayout')

  const emotionalAnalysis = await page.evaluate(() => {
    const text = document.querySelectorAll('.jgy_txt.jgy_txt_isLayout')[1].innerText
    return text
  })

  sentiment['情绪温度'] = emotionalAnalysis.replace('经过AI分析显示：', '')


  // 访问热榜
  await page.goto('https://eq.10jqka.com.cn/webpage/new-header-square/index.html#/')

  const cookies = await browser.cookies();

  // 将 cookies 转换为 fetch 请求的 Cookie 头部格式
  const cookieHeader = cookies
    .map(cookie => `${cookie.name}=${cookie.value}`)  // 将每个 cookie 转换为 "name=value"
    .join('; ');  // 将所有 cookies 用分号连接起来

  // 访问行业和热点数据
  const marketInformation = await getIndustryData(cookieHeader)

  const allData = {
    ...marketInformation,
    '市场情绪': sentiment,
    '股票数据': stockList,
  }

  // 保存数据
  saveStock(allData);

  // page.close()

  browser.close()

})();

